package com.cskaoyan.user.controller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dto.KaptchaCodeResponse;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("user")
public class UserRegisterController {

    @Autowired
    IUserRegisterService userRegisterService;
    @Autowired
    IKaptchaService kaptchaService;

    /**
     * @Author Chen
     * @Date 2022-09-20  21-37-24
     * @param
     * @return {@link null }
     * @description  新用户注册
     */
    @PostMapping("register")
    public ResponseData register(@RequestBody UserRegisterRequest userRegister, HttpServletRequest request){

        ResponseUtil responseUtil = new ResponseUtil();

        //获取验证码
        String kaptchaUuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        String captcha = userRegister.getCaptcha();

        KaptchaCodeRequest kaptchaCodeVerify = new KaptchaCodeRequest();
        kaptchaCodeVerify.setUuid(kaptchaUuid);
        kaptchaCodeVerify.setCode(captcha);

        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeVerify);
        String imageCode = kaptchaCodeResponse.getImageCode();

        //判断验证码是否正确
        if (!imageCode.equalsIgnoreCase(captcha)){
            ResponseData loginError = responseUtil.setErrorMsg("验证码错误");
            return loginError;
        }

        UserRetCode userRetCode = userRegisterService.register(userRegister);


        if (userRetCode==UserRetCode.USERNAME_ALREADY_EXISTS){
            ResponseData responseData = responseUtil.setErrorMsg("用户已存在");
            return responseData;
        }

        ResponseData responseData = responseUtil.setData(null);

        return responseData;
    }


    @GetMapping("verify")
    public ResponseData userActive(UserVerifyRequest userVerify){


        UserRetCode verify = userRegisterService.verify(userVerify);

        ResponseUtil responseUtil = new ResponseUtil();

        if (verify == UserRetCode.SUCCESS){
            ResponseData responseData = responseUtil.setData(null, "恭喜您的账户已激活成功，快去购物吧！");
            responseData.setSuccess(true);
            return responseData;
        }

        ResponseData responseData = responseUtil.setErrorMsg("激活失败，请稍后再试");
        responseData.setSuccess(false);
        return responseData;
    }
}
